package net.tv90.bfmccore.game.view;

import lk.vexview.api.VexViewAPI;
import lk.vexview.builders.ButtonBuilder;
import lk.vexview.builders.GuiBuilder;
import lk.vexview.builders.ImageBuilder;
import lk.vexview.gui.OpenedVexGui;
import lk.vexview.gui.VexGui;
import lk.vexview.gui.components.DynamicComponent;
import lk.vexview.gui.components.VexButton;
import lk.vexview.gui.components.VexHoverText;
import lk.vexview.gui.components.VexImage;
import net.tv90.bfmccore.game.GameBase;
import net.tv90.bfmccore.game.GameManager;
import net.tv90.bfmccore.squad.Squad;
import net.tv90.bfmccore.util.Cooldown;
import org.bitterorange.flansmodslain.FlansModAPI;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.*;

import static net.tv90.bfmccore.helper.FactionHelper.getCountry2;
import static net.tv90.bfmccore.helper.FactionHelper.getKit2;

public class GameViewManager implements Runnable {

    //刷新率，单位赫兹 (最大20，为每tick更新一次)
    public static final int TICK_RATE = 5;
    public static volatile GameViewManager instance;

    private GameViewManager() {
    }

    public static GameViewManager getInstance() {
        if (instance == null) {
            synchronized (GameViewManager.class) {
                if (instance == null) {
                    instance = new GameViewManager();
                }
            }
        }
        return instance;
    }

    public void tick(int tickRate) {
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (!GameModelViewHandler.vexViewVerificationPlayers.contains(player.getName())) {
                continue;
            }
            OpenedVexGui vexGui = VexViewAPI.getPlayerCurrentGui(player);
            if (vexGui == null) {
                continue;
            }
            int windowWidth = VexViewAPI.getPlayerClientWindowWidth(player);
            int windowHeight = VexViewAPI.getPlayerClientWindowHeight(player);

            GameBase game = GameManager.getInstance().currentGame;

            switch (game.getGameType()) {
                case GUNMASTER:
                case START:
                case TDM: {
                    //更新部署按钮
                    VexButton deployBtn = vexGui.getVexGui().getButtonById("DeployButton");
                    if (deployBtn != null) {
                        vexGui.removeDynamicComponent(deployBtn);
                        VexButton newDeployBtn = ButtonBuilder.builder()
                                .id("DeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 380 * windowHeight / 445)
                                .text("随机部署至战场" + (Cooldown.getTime("Deploy", player) > 0 ? Cooldown.getTime("Deploy", player) : "0") + ".0s")
                                .clickable(Cooldown.getTime("Deploy", player) <= 0)
                                .click(GameModelViewHandler.getInstance()::deploy)
                                .build();
                        vexGui.addDynamicComponent(newDeployBtn);
                    }
                    //更新小队部署按钮
                    VexButton squadDeployBtn = vexGui.getVexGui().getButtonById("SquadDeployButton");
                    if (squadDeployBtn != null) {
                        vexGui.removeDynamicComponent(squadDeployBtn);
                        VexButton newSquadDeployBtn = ButtonBuilder.builder()
                                .id("SquadDeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 340 * windowHeight / 445)
                                .text("部署至小队长 " + (Cooldown.getTime("Teleport", player) > 0 ? Cooldown.getTime("Teleport", player) : "0") + ".0s")
                                .clickable(Cooldown.getTime("Teleport", player) <= 0)
                                .click(Squad::teleportToLeader)
                                .build();
                        vexGui.addDynamicComponent(newSquadDeployBtn);
                    }
                    break;
                }
                case SDM: {
                    //更新部署按钮
                    VexButton deployBtn = vexGui.getVexGui().getButtonById("DeployButton");
                    if (deployBtn != null) {
                        vexGui.removeDynamicComponent(deployBtn);
                        VexButton newDeployBtn = ButtonBuilder.builder()
                                .id("DeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 380 * windowHeight / 445)
                                .text("小队长部署 " + (Cooldown.getTime("Deploy", player) > 0 ? Cooldown.getTime("Deploy", player) : "0") + ".0s")
                                .clickable(Cooldown.getTime("Deploy", player) <= 0)
                                .click(GameModelViewHandler.getInstance()::deploy)
                                .build();
                        vexGui.addDynamicComponent(newDeployBtn);
                    }
                    VexButton squadDeployBtn = vexGui.getVexGui().getButtonById("SquadDeployButton");
                    if (squadDeployBtn != null) {
                        vexGui.removeDynamicComponent(squadDeployBtn);
                        VexButton newSquadDeployBtn = ButtonBuilder.builder()
                                .id("SquadDeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 340 * windowHeight / 445)
                                .text("队员部署 " + (Cooldown.getTime("Teleport", player) > 0 ? Cooldown.getTime("Teleport", player) : "0") + ".0s")
                                .clickable(Cooldown.getTime("Teleport", player) <= 0)
                                .click(Squad::teleportToLeader)
                                .build();
                        vexGui.addDynamicComponent(newSquadDeployBtn);
                    }
                    break;
                }
                case CONQUEST:
                case FRONTLINE:
                case VEHICLE_STORM:
                case AIR_SUPERIORITY: {
                    //更新部署按钮
                    VexButton deployBtn = vexGui.getVexGui().getButtonById("DeployButton");
                    if (deployBtn != null) {
                        vexGui.removeDynamicComponent(deployBtn);
                        VexButton newDeployBtn = ButtonBuilder.builder()
                                .id("DeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 380 * windowHeight / 445)
                                .text("点击蓝色占领点部署" + (Cooldown.getTime("Deploy", player) > 0 ? Cooldown.getTime("Deploy", player) : "0") + ".0s")
                                .clickable(false)
                                .click(GameModelViewHandler.getInstance()::deploy)
                                .build();
                        vexGui.addDynamicComponent(newDeployBtn);
                    }
                    //更新小队部署按钮
                    VexButton squadDeployBtn = vexGui.getVexGui().getButtonById("SquadDeployButton");
                    if (squadDeployBtn != null) {
                        vexGui.removeDynamicComponent(squadDeployBtn);
                        VexButton newSquadDeployBtn = ButtonBuilder.builder()
                                .id("SquadDeployButton")
                                .background("[local]GUI/button.png", "[local]GUI/button_focus.png")
                                .unClickable("[local]GUI/button_unclickable.png")
                                .size(100 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(720 * windowWidth / 854, 340 * windowHeight / 445)
                                .text("部署至小队长 " + (Cooldown.getTime("Teleport", player) > 0 ? Cooldown.getTime("Teleport", player) : "0") + ".0s")
                                .clickable(Cooldown.getTime("Teleport", player) <= 0)
                                .click(Squad::teleportToLeader)
                                .build();
                        vexGui.addDynamicComponent(newSquadDeployBtn);
                    }
                    //更新部署到载具上按钮
                    // 部署至步战车（IFV）
                    VexButton ifvBtn = vexGui.getVexGui().getButtonById("IFVDeployButton");
                    vexGui.removeDynamicComponent(ifvBtn);
                    if (ifvBtn != null) {
                        VexButton newIfvBtn = ButtonBuilder.builder()
                                .id("IFVDeployButton")
                                .background("[local]GUI/MenuVehicleIFVXL.png", "[local]GUI/MenuVehicleIFVXL_1.png")
                                .unClickable("[local]GUI/MenuVehicleIFVXL_2.png")
                                .size(30 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(680 * windowWidth / 854, 340 * windowHeight / 445)
                                .text("")
                                .hover(new VexHoverText(Collections.singletonList("部署至友军随机步战车")))
                                .clickable(GameManager.getInstance().currentGame.maxTankNum > 0)
                                .click(p -> GameManager.getInstance().currentGame.deployOnRandomAircraftEntity(p, "IFV"))
                                .build();
                        vexGui.addDynamicComponent(newIfvBtn);
                    }
                    // 部署至轻型载具（Transport）
                    VexButton transportBtn = vexGui.getVexGui().getButtonById("TransportDeployButton");
                    vexGui.removeDynamicComponent(transportBtn);
                    if (transportBtn != null) {
                        VexButton newTransportBtn = ButtonBuilder.builder()
                                .id("TransportDeployButton")
                                .background("[local]GUI/MenuVehicleJeepArmoredXL.png", "[local]GUI/MenuVehicleJeepArmoredXL_1.png")
                                .unClickable("[local]GUI/MenuVehicleJeepArmoredXL_2.png")
                                .size(30 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(640 * windowWidth / 854, 340 * windowHeight / 445)
                                .text("")
                                .hover(new VexHoverText(Collections.singletonList("部署至友军随机轻型运输载具")))
                                .clickable(GameManager.getInstance().currentGame.maxLightVehicleNum > 0)
                                .click(p -> GameManager.getInstance().currentGame.deployOnRandomAircraftEntity(p, "Transport"))
                                .build();
                        vexGui.addDynamicComponent(newTransportBtn);
                    }
                    // 部署至快艇（FAC）
                    VexButton facBtn = vexGui.getVexGui().getButtonById("FACDeployButton");
                    vexGui.removeDynamicComponent(facBtn);
                    if (facBtn != null) {
                        VexButton newFacBtn = ButtonBuilder.builder()
                                .id("FACDeployButton")
                                .background("[local]GUI/MenuVehicleBoatFastAttackXL.png", "[local]GUI/MenuVehicleBoatFastAttackXL_1.png")
                                .unClickable("[local]GUI/MenuVehicleBoatFastAttackXL_2.png")
                                .size(30 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(680 * windowWidth / 854, 380 * windowHeight / 445)
                                .text("")
                                .hover(new VexHoverText(Collections.singletonList("部署至友军随机攻击快艇")))
                                .clickable(GameManager.getInstance().currentGame.maxFacNum > 0)
                                .click(p -> GameManager.getInstance().currentGame.deployOnRandomAircraftEntity(p, "FAC"))
                                .build();
                        vexGui.addDynamicComponent(newFacBtn);
                    }
                    // 部署至侦察直升机（ScoutHeli / 运输机）
                    VexButton scoutHeliBtn = vexGui.getVexGui().getButtonById("ScoutHeliDeployButton");
                    vexGui.removeDynamicComponent(scoutHeliBtn);
                    if (scoutHeliBtn != null) {
                        VexButton newScoutHeliBtn = ButtonBuilder.builder()
                                .id("ScoutHeliDeployButton")
                                .background("[local]GUI/MenuVehicleScoutHeliXL.png", "[local]GUI/MenuVehicleScoutHeliXL_1.png")
                                .unClickable("[local]GUI/MenuVehicleScoutHeliXL_2.png")
                                .size(30 * windowWidth / 854, 30 * windowHeight / 445)
                                .location(640 * windowWidth / 854, 380 * windowHeight / 445)
                                .text("")
                                .hover(new VexHoverText(Collections.singletonList("部署至友军随机运输直升机")))
                                .clickable(GameManager.getInstance().currentGame.maxTransHeliNum > 0)
                                .click(p -> GameManager.getInstance().currentGame.deployOnRandomAircraftEntity(p, "ScoutHeli"))
                                .build();
                        vexGui.addDynamicComponent(newScoutHeliBtn);
                    }
                    break;
                }
            }

            //渲染地图上的玩家
            if (game.mapCoordConverter != null && vexGui.getVexGui().getButtonById("DeployButton") != null) {
                Set<Player> list = null;
                if (GameBase.firstFactionList.contains(player)) {
                    list = GameBase.firstFactionList;
                }
                if (GameBase.secondFactionList.contains(player)) {
                    list = GameBase.secondFactionList;
                }
                if (list == null) continue;
                for (Player p : list) {
                    String text = p.getName();
                    if (text.length() > 12) {
                        text = text.substring(0, 9) + "..";
                    }
                    String path = "[local]BattleField/player.png";
                    if (p.getName().equals(Squad.getLeader(player))) {
                        path = "[local]BattleField/player_squadleader.png";
                        text = "§a" + text;
                    }
                    if (!GameManager.inBattleFieldPlayers.contains(p)) {
                        path = "[local]BattleField/player_dead.png";
                        text = "";
                    }
                    if(p.getVehicle() != null) {
                        String vehicle = FlansModAPI.getPlayerVehicle(p);
                        if (!"AIR".equals(vehicle) && !"PASSENGER".equals(vehicle)) {
                            text += "[" + vehicle + "]";
                        }
                    }
                    int x = game.mapCoordConverter.worldToScreen(p.getLocation().getBlockX(), p.getLocation().getBlockZ())[0];
                    int z = game.mapCoordConverter.worldToScreen(p.getLocation().getBlockX(), p.getLocation().getBlockZ())[1];
                    VexButton playerImage = vexGui.getVexGui().getButtonById(p.getName() + "_btn");
                    vexGui.removeDynamicComponent(playerImage);
                    VexButton newPlayerImage = ButtonBuilder.builder()
                            .id(p.getName() + "_btn")
                            .background(path, path)
                            .unClickable(path)
                            .size(10 * windowWidth / 854, 10 * windowHeight / 445)
                            .location(x * windowWidth / 854, z * windowHeight / 445)
                            .text(text)
                            .clickable(false)
                            .build();
                    vexGui.addDynamicComponent(newPlayerImage);
                }
            }
        }
    }

    @Override
    public void run() {
        tick(TICK_RATE);
    }
}
